/**
 * Description: 使用poll实现IO多路复用
 * File: server.c |Time: 2021-04-16 17:00
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <poll.h>

#define ERR(msg) do {   \
    perror(msg);        \
    fprintf(stderr, "[err at]%s:%s:%d\n", __FILE__, __func__, __LINE__); \
    exit(EXIT_FAILURE); \
} while (0)

#define BUF_SIZE 128

typedef struct sockaddr * saddr;


int main(int argc, char *argv[])
{
    if (argc < 3) {
        fprintf(stderr, "Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == sockfd) {
        ERR("socket");
    }

    struct sockaddr_in serveraddr, clientaddr;
    socklen_t addrlen = sizeof(serveraddr);
    memset(&serveraddr, 0, sizeof(struct sockaddr_in));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (-1 == bind(sockfd, (saddr)&serveraddr, addrlen)) {
        ERR("bind");
    }

    if (-1 == listen(sockfd, 5)) {
        ERR("listen");
    }

    char buf[BUF_SIZE];
    int acceptfd;
    int rw_bytes;
    struct pollfd pfds[2];
    int nfds = 2;
    acceptfd = accept(sockfd, (saddr)&clientaddr, &addrlen);
    if (-1 == acceptfd) {
        ERR("accept");
    }
    pfds[0].fd = 0;
    pfds[0].events = POLLIN;
    pfds[1].fd = acceptfd;
    pfds[1].events = POLLIN;

    printf("input whatever you want.\n");
    while (1) {
        if (-1 == poll(pfds, nfds, -1)) {
            ERR("poll");
        }

        for (int i = 0; i < nfds; i++) {
            if (i == 0 && (pfds[i].revents & POLLIN)) {
                // 阻塞部分1等待输入并打印
                bzero(buf, BUF_SIZE);
                fgets(buf, BUF_SIZE, stdin);
                printf("input str: %s\n", buf);
            }

            if (i == 1 && (pfds[i].revents & POLLIN)) {
                // 阻塞部分2客户端连接后recv阻塞接收客户端信息
                bzero(buf, BUF_SIZE);
                rw_bytes = recv(acceptfd, buf, BUF_SIZE, 0);
                if (-1 == rw_bytes) {
                    ERR("recv");
                }
                printf("[from client :%s:%d] %s\n", 
                        inet_ntoa(clientaddr.sin_addr), 
                        ntohs(clientaddr.sin_port), 
                        buf);
                sprintf(buf, "[server] %s received ^_^", buf);
                rw_bytes = send(acceptfd, buf, BUF_SIZE, 0);
                if (-1 == rw_bytes) {
                    ERR("send");
                }        
            }
        }
    }

    if (-1 == close(sockfd)) {
        ERR("close");
    }

    return 0;
}


